package jman.servlet;

import java.io.IOException;
import java.sql.SQLException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import jman.service.UserService;
import jman.service.VoteService;

/**
 * Servlet implementation class DoVote
 */
public class DoVote extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public DoVote() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		HttpSession session=request.getSession();
		if(session.getAttribute("id")==null){
			request.getRequestDispatcher("/jman/admin/login.html").forward(request, response);
		}else{
			if(request.getParameter("user_id")!=null){
				boolean flag=false;
				int id=(int) session.getAttribute("id");
				int vote_Id=(int) session.getAttribute("vote_Id");
				int user_Id=Integer.valueOf(request.getParameter("user_id"));
				UserService us=new UserService();
				try {
					flag=us.vote(id,vote_Id,user_Id);
				} catch (SQLException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				if(flag){
					VoteService vs=new VoteService();
					try {
						session.setAttribute("voteList",vs.getListForStudent(id));
						session.setAttribute("voteList1",vs.getListForStudentToVote(id));
						session.setAttribute("number",vs.getListForStudentToVote(id).size());
					} catch (SQLException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					request.getRequestDispatcher("/jman/admin/stadmin.jsp").forward(request, response);
				}else{
					request.getRequestDispatcher("DoVoteFail.jsp").forward(request, response);
				}
			}
		}
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}
